<template>
  <div class="app-container">
    <transition :enter-active-class="animate.searchAnimate.enter" :leave-active-class="animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="80px">
            <el-form-item label="商户名称" prop="account" v-if="isAdmin">
              <el-input v-model="queryParams.createName" placeholder="请输入商户名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="C端订单号" prop="orderId">
              <el-input v-model="queryParams.orderId" placeholder="请输入C端订单号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="B端订单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入B端订单号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="接收邮箱" prop="receiveEmail">
              <el-input v-model="queryParams.receiveEmail" placeholder="请输入接收邮箱" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="发送邮箱" prop="sendEmailAct">
              <el-input v-model="queryParams.sendEmailAct" placeholder="请输入发送邮箱" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in email_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['system:EmailList:remove']"
                type="danger"
                plain
                icon="Delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailQueue:remove']" type="danger" plain icon="Delete" size="mini" @click="handleDeleteAll"
                >全部删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailList:export']" type="warning" plain icon="Download" size="mini" @click="handleExport"
                >导出
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailList:resend']" type="primary" plain icon="Promotion" size="mini" @click="handleReSend()"
                >一键重发失败邮件
              </el-button>
            </el-col>
          </el-row>
          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="EmailListList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="发送时间" align="center" prop="sendTime" width="200" />
        <el-table-column label="商户名称" v-if="isAdmin" align="center" prop="createName" />
        <el-table-column label="发件人账号" align="center" prop="sendEmailAct" width="220" />
        <el-table-column label="接收账号" align="center" prop="receiveEmail" width="220" />
        <el-table-column label="C端订单号" align="center" prop="orderId">
          <template #default="{ row }">
            <el-link class="truncate overflow-hidden max-w-[100%]" :underline="false" @click="copyText(row.orderId, 'C端订单号')">{{
              row.orderId
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="B端订单号" align="center" prop="orderNo" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link class="truncate overflow-hidden max-w-[100%]" :underline="false" @click="copyText(row.orderNo, 'B端订单号')">{{
              row.orderNo
            }}</el-link>
          </template>
        </el-table-column>

        <el-table-column label="动态参数" align="center" prop="dyncParam" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="email_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="报错时间" align="center" prop="errTime" width="150" />
        <el-table-column label="报错内容" align="center" prop="errContent" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="150" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
          <template #default="scope">
            <el-button
              v-if="scope.row.status == 4"
              v-hasPermi="['system:EmailList:resend']"
              size="mini"
              text
              type="primary"
              icon="Promotion"
              @click="handleReSend([scope.row.emailId])"
              >失败重发
            </el-button>
            <el-button text type="primary" icon="Document" @click="viewEmail(scope.row)">查看邮件 </el-button>
            <el-button v-hasPermi="['system:EmailList:remove']" size="mini" text type="primary" icon="Delete" @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>

    <!-- 添加或修改邮件列表对话框 -->
    <el-dialog v-model:visible="open" :title="title" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="接收账号" prop="receiveEmail">
          <el-input v-model="form.receiveEmail" placeholder="请输入接收账号" />
        </el-form-item>
        <el-form-item label="动态参数" prop="dyncParam">
          <el-input v-model="form.dyncParam" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看邮件队列对话框 -->
    <el-dialog v-model="viewDialog" :title="title" width="80%" append-to-body>
      <el-form ref="form" label-width="80px">
        <el-form-item label="邮件主题" prop="theme">
          <el-input v-model="theme" placeholder="请输入邮件主题" disabled />
        </el-form-item>
        <el-form-item label="邮件内容">
          <!--          <editor v-model="form.template" :min-height="192"/>-->
          <vue-ueditor-wrap v-model="viewContent" :config="ueditorConfig"></vue-ueditor-wrap>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewCancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="reSendVisible" width="700" title="选择发送邮箱">
      <el-form inline label-width="auto">
        <el-form-item label="是否更改发送邮箱">
          <el-switch v-model="showChangeEmail"></el-switch>
        </el-form-item>
        <el-form-item label="邮箱账号" v-if="showChangeEmail">
          <el-input v-model="reSendEmail" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <el-table v-if="showChangeEmail" class="mt-[20px]" v-loading="loading" :data="emailAccountData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="邮箱账号" align="center" prop="account" />
      </el-table>

      <template #footer>
        <el-button>确定</el-button>
        <el-button>取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listEmailList, getEmailList, delEmailList, addEmailList, reSend, updateEmailList, deleteAllEmail } from '@/api/email/EmailList';
import { listEmailAccount } from '@/api/email/EmailAccount';
import useUserStore from '@/store/modules/user';
import { copyTextToClipboard } from '@/directive/common/copyText';
export default {
  name: 'EmailList',
  data() {
    return {
      email_status: [],
      emailAccount: [],
      showChangeEmail: false,
      reSendEmail: '',
      reSendVisible: false,
      ueditorConfig: {
        UEDITOR_HOME_URL: '/ueditor/',
        toolbars: [
          [
            'source', //源代码
            'undo', //撤销
            'redo', //重做
            'bold', //加粗
            'indent', //首行缩进
            'snapscreen', //截图
            'italic', //斜体
            'underline', //下划线
            'print', //打印
            'horizontal', //分隔线
            'inserttable', //插入表格
            'edittable', //表格属性
            'insertrow', //前插入行
            'insertcol', //前插入列
            'mergeright', //右合并单元格
            'mergedown', //下合并单元格
            'deleterow', //删除行
            'deletecol', //删除列
            'splittorows', //拆分成行
            'splittocols', //拆分成列
            'splittocells', //完全拆分单元格
            'deletecaption', //删除表格标题
            'inserttitle', //插入标题
            'mergecells', //合并多个单元格
            'edittd', //单元格属性
            'deletetable', //删除表格
            // 'fontfamily', //字体
            // 'fontsize', //字号
            // 'paragraph', //段落格式
            'simpleupload', //单图上传
            'insertimage', //多图上传
            'attachment', //附件
            'link', //超链接
            'emotion', //表情
            'spechars', //特殊字符
            'searchreplace', //查询替换
            'map', //Baidu地图
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对齐
            'justifyjustify', //两端对齐
            'forecolor', //字体颜色
            'backcolor', //背景色
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'rowspacingtop', //段前距
            'rowspacingbottom', //段后距
            'lineheight', //行间距
            'autotypeset', //自动排版
            'template', //模板
            'scrawl' //涂鸦
          ]
        ],
        autoHeightEnabled: true,
        initialFrameHeight: 300
      },
      viewContent: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 邮件列表表格数据
      EmailListList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查看弹窗
      viewDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        type: 1,
        receiveEmail: null,
        sendEmailId: null,
        sendEmailAct: null,
        status: null,
        errContent: null
      },
      // 表单参数
      form: {},
      // 邮件主题
      theme: '',
      // 表单校验
      rules: {}
    };
  },
  async created() {
    let res = await this.useDict('email_status');
    await this.getList();
    setTimeout(() => {
      this.email_status = res.email_status;
    }, 1000);
  },
  computed: {
    isAdmin() {
      const { isAdmin } = useUserStore();
      return isAdmin;
    },
    emailAccountData() {
      return this.emailAccount.filter((item) => item.account.includes(this.reSendEmail));
    }
  },
  methods: {
    // 复制成功
    copyText(str, msg) {
      if (!str) return;
      let newStr = str + '';
      let res = copyTextToClipboard(newStr);
      if (res) {
        ElMessage.success(msg + '复制成功');
      }
    },
    async handleReSendPro() {
      let res = await listEmailAccount({ isPage: false });
      this.emailAccount = res.rows.filter((item) => item.status == 0);
      this.reSendVisible = true;
    },
    handleReSend(emailIds) {
      let params = {};

      if (emailIds !== undefined && emailIds !== null && emailIds.length > 0) {
        params.emailIds = emailIds;
      }

      reSend(params).then((response) => {
        this.$modal.msgSuccess('重发成功');
        this.open = false;
        this.getList();
      });
    },
    // 查看关闭
    viewCancel() {
      this.viewDialog = false;
    },
    /** 查看邮件信息 */
    viewEmail(row) {
      this.theme = '';
      this.viewContent = '';

      getEmailList(row.emailId).then((response) => {
        this.theme = response.data.theme;
        this.viewContent = response.data.emailContent;
        this.viewDialog = true;
        this.title = '邮件详情';
      });
    },
    /** 查询邮件列表列表 */
    getList() {
      this.loading = true;
      listEmailList(this.queryParams).then((response) => {
        this.EmailListList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        emailId: null,
        queueId: null,
        receiveEmail: null,
        dyncParam: null,
        sendEmailId: null,
        sendEmailAct: null,
        sendTime: null,
        status: null,
        isDelete: null,
        errTime: null,
        errContent: null,
        deptId: null,
        createId: null,
        createName: null,
        createTime: null,
        updateId: null,
        updateName: null,
        updateTime: null
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        type: 1,
        receiveEmail: null,
        sendEmailId: null,
        sendEmailAct: null,
        status: null,
        errContent: null
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.emailId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加邮件列表';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const emailId = row.emailId || this.ids;
      getEmailList(emailId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = '修改邮件列表';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.emailId != null) {
            updateEmailList(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addEmailList(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const emailIds = row.emailId || this.ids;
      this.$modal
        .confirm('是否确认删除邮件列表编号为"' + emailIds + '"的数据项？')
        .then(function () {
          return delEmailList(emailIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 全部删除按钮操作 */
    handleDeleteAll(row) {
      this.$modal
        .confirm('是否确认删除所有邮件记录？')
        .then(function () {
          return deleteAllEmail(1);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/EmailList/export',
        {
          ...this.queryParams
        },
        `EmailList_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-link) {
  display: inline-block;
  .el-link__inner {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
